<script lang="ts">
import { useAntdForm } from '@peng_kai/kit/antd';
import Turnstile, { cfRules } from '~comp/Turnstile.vue';

export const sendEmailAgainPopup = useAntdModal(
  // eslint-disable-next-line import/no-self-import
  defineAsyncComponent(() => import('./SendEmailAgain.vue')),
  {
    title: computed(() => 'Please verify'),
    wrapClassName: 'ant-cover__Modal-drawer',
    width: 400,
    centered: true,
    maskClosable: false,
    footer: null,
    rejectOnClose: true,
  },
);
</script>

<script setup lang="ts">
const props = defineProps<{
  email: string;
  type: number;
  onClose?: () => void;
  onSuccess?: () => void;
}>();

const form = useAntdForm({
  cf_turnstile_response: {
    value: '',
    rules: cfRules,
  },
});

const turnstileDomRef = ref();

const sendEmailMut = useMutation({
  mutationKey: [apis.apiEmailSendVerify.id],
  mutationFn: apis.apiEmailSendVerify.setDefaultConfig({
    successMessage: $t('3eLLjpddCNugNkCsdDpl'),
  }),
  onSuccess() {
    props.onSuccess?.();
    props.onClose?.();
  },
  onError() {
    turnstileDomRef.value?.reset?.();
    form.$form?.clearValidate?.();
  },
});

const getIsLoadingRef = computed(() => sendEmailMut.isPending.value);

async function handleSubmit() {
  if (!(await form.$form?.validate?.().catch(() => false)) || !props.email || !props.type)
    return;

  sendEmailMut.mutate({ requestBody: { ...props, ...form.state } });
}
</script>

<template>
  <AForm v-bind="form.props" class="ant-cover__Form-compact" :disabled="getIsLoadingRef" @finish="handleSubmit">
    <AFormItem v-bind="form.itemProps.cf_turnstile_response">
      <Turnstile ref="turnstileDomRef" v-model:value="form.state.cf_turnstile_response" />
    </AFormItem>
    <AButton
      class="ant-cover__Button-3d-primary mt-4" type="primary" block htmlType="submit"
      :disabled="getIsLoadingRef" :loading="getIsLoadingRef"
    >
      {{ $t('fVhxPoy2u9I4Q6dqrMh') }}
    </AButton>
  </AForm>
</template>
